package com.xjm.api.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xjm.entity.model.OrdersModel;
import com.xjm.entity.model.TrackingModel;
import com.xjm.entity.vo.Result;
import com.xjm.service.IOrdersService;
import com.xjm.service.ITrackingService;
import com.xjm.utils.SpaceApiUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xjm
 * @since 2025-03-10
 */
@RestController
@RequestMapping("/user/tracking")
@RequiredArgsConstructor
public class WebTrackingController {

    private final IOrdersService ordersService;

    private final ITrackingService trackingService;

    @GetMapping("/{orderNo}")
    public Result<?> getTrackByOrderSn(@PathVariable String orderNo) {
        LambdaQueryWrapper<OrdersModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrdersModel::getOrderNo, orderNo);
        OrdersModel ordersModel = ordersService.getOne(wrapper);
        if (ordersModel == null) return Result.error("订单不存在");
        LambdaQueryWrapper<TrackingModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TrackingModel::getOrderId, ordersModel.getId());
        TrackingModel one = trackingService.getOne(queryWrapper);
        if (one == null) return Result.error("暂无物流信息");
        if (one.getEnd() == 1) return Result.success(one);
        TrackingModel orderStatus = SpaceApiUtil.getOrderStatus(one.getTraceNo(), one.getCpCode());
        if (orderStatus == null) {
            return Result.error("暂无物流信息");
        }
        if (orderStatus.getEnd() == 1) {
            one.setTrace(orderStatus.getTrace());
            one.setTheLastTime(orderStatus.getTheLastTime());
            one.setEnd(1);
            trackingService.updateById(one);
        }
        return Result.success(orderStatus);
    }
}
